#include "Precompile.h"
#include "SMQuadTree.h"
#include "Model.h"
#include "ICamera.h"

namespace Graphics{
	SMQuadTree::SMQuadTree():m_entityId(0),m_minQuadSize(10){
		m_connection = RenderSystem::RenderingEvent.registerHandler(this,&SMQuadTree::render);
	}

	SMQuadTree::~SMQuadTree(){
		
	}

	void SMQuadTree::render(RenderContext *context){
		m_renderObjects.clear();

		boost::shared_ptr<Mesh> mesh;
		std::map<unsigned int, EntityPtr>::iterator itr = m_entitys.begin();
		while(itr != m_entitys.end()){
			if(itr->second->m_type == Entity::ET_MESH){
				mesh = boost::static_pointer_cast<Mesh>(itr->second);
				m_renderObjects[mesh->getModelId()].push_back(mesh->m_id);
			}
			itr++;
		}
	}
	
	unsigned int SMQuadTree::addEntity(boost::shared_ptr<Entity> entity){
		unsigned int id = m_entityId++;
		entity->m_id = id;

		switch(entity->m_type){
		case Entity::ET_MESH:
			{
				MeshPtr mesh = boost::static_pointer_cast<Mesh>(entity);
				m_renderSystem->addMesh(mesh);
				break;
			}
		case Entity::ET_CAMERA:
			{
				m_renderSystem->registerCamera(boost::static_pointer_cast<Utility::ICamera>(entity));
				break;
			}
		case Entity::ET_LIGHT:
			{

				break;
			}
		default:
			break;
		}

		m_entitys[id] = entity;
		return id;
	}

	void SMQuadTree::removeEntity(unsigned int id){
		std::map<unsigned int, EntityPtr>::iterator itr = m_entitys.find(id);
		if(itr == m_entitys.end()){
			LOG_ERROR("Entity does not exist.");
			assert(0);
			return;
		}

		switch(itr->second->m_type){
			case Entity::ET_MESH:
			{
				MeshPtr mesh = boost::static_pointer_cast<Mesh>(itr->second);
				m_renderSystem->removeMesh(mesh);
				break;
			}
		case Entity::ET_CAMERA:
			{
				break;
			}
		default:
			break;
		}

		m_entitys.erase(itr);
	}

	EntityPtr SMQuadTree::getEntity(unsigned int id){
		if(m_entitys.find(id) == m_entitys.end())
			return EntityPtr();

		return m_entitys[id];
	}
}